<template>
  <div>
    <van-nav-bar
      :title="title"
      left-arrow
      @click-left="$emit('close')"
    />
    <van-form ref="submitForm" @submit="doSubmit">
      <van-field
        readonly
        clickable
        :value="submitForm.date"
        label="日期选择"
        placeholder="点击选择日期"
        input-align="left"
        :rules="[{ required: true, message: '请选择日期' }]"
        @click="showDate = true"
      />
      <van-field
        v-model="submitForm.processName"
        label="工序"
        input-align="left"
        placeholder="请选择工序"
        :rules="[{ required: true, message: '请选择工序' }]"
        clickable
        readonly
        @click="showProcess=true"
      />
      <div style="padding-left: 0.5em;padding-top: 0.5em">
        <div v-for="(item,index) in employeeList" :key="index" style="display: inline;padding: 10px;">
          <van-tag style="padding: 5px;margin-top: 10px" closeable type="primary" plain size="medium" @close="handleRemoveEmployee(item)">{{ item.employeeName }}</van-tag>
        </div>
        <van-cell v-if="submitForm.processId">
          <template #default>
            <van-button icon="plus" size="small" native-type="button" @click="showEmployee = true">添加员工</van-button>
          </template>
        </van-cell>
      </div>
      <van-field
        v-if="submitForm.processId"
        v-model="submitForm.unitPrice"
        readonly
        label="工序单价"
        type="number"
        placeholder="请输入工序单价"
        input-align="left"
      />
      <van-field
        v-model="submitForm.shiftName"
        label="班次"
        input-align="left"
        placeholder="请选择班次"
        :rules="[{ required: true, message: '请选择班次' }]"
        clickable
        readonly
        @click="showShift=true"
      />
      <van-field
        v-model="submitForm.quantity"
        readonly
        label="产量"
        type="digit"
        placeholder="请输入产量"
        input-align="left"
      />
      <van-field
        v-model="submitForm.subsidy"
        label="补贴"
        type="number"
        placeholder="请输入补贴"
        input-align="left"
      />
      <van-cell-group v-if="submitForm.quantity!==''&&submitForm.unitPrice!==''&&employeeList.length>0">
        <van-col :span="12">
          <van-cell title="共计">
            <template #default>
              {{ (submitForm.quantity * submitForm.unitPrice).toFixed(2) }}元
            </template>
          </van-cell>
        </van-col>
        <van-col :span="12">
          <van-cell title="每人">
            <template #default>
              {{ (submitForm.quantity * submitForm.unitPrice / submitForm.employeeIds.length).toFixed(2) }}元
            </template>
          </van-cell>
        </van-col>
        <van-col :span="12">
          <van-cell title="补贴">
            <template #default>
              {{ submitForm.subsidy }}元
            </template>
          </van-cell>
        </van-col>
        <van-col :span="12">
          <van-cell title="补贴后每人">
            <template #default>
              {{ (submitForm.quantity * submitForm.unitPrice / submitForm.employeeIds.length + Number(submitForm.subsidy)).toFixed(2) }}元
            </template>
          </van-cell>
        </van-col>
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="danger" native-type="submit">提交</van-button>
      </div>
    </van-form>
    <van-calendar v-model="showDate" :min-date="minDate" :show-confirm="false" @confirm="onConfirmDate" />
    <van-popup v-model="showShift" position="bottom">
      <van-picker
        show-toolbar
        :columns="shiftList"
        @confirm="onShiftConfirm"
        @cancel="showShift = false"
      />
    </van-popup>
    <van-popup v-model="showProcess" position="bottom">
      <van-picker
        show-toolbar
        :columns="processList"
        @confirm="onProcessConfirm"
        @cancel="showProcess = false"
      />
    </van-popup>
    <div v-if="showEmployee">
      <select-employee ref="employeeModule" :disable-ids="submitForm.employeeIds" :visible="showEmployee" @close="handleCloseEmployee" />
    </div>
  </div>
</template>

<script>
import { calculatePieceRateWage } from '@/api/pieceRateWage'
import moment from 'moment'
import Moment from 'moment/moment'
import { selectAllShift } from '@/api/shift'
import { selectAllProcess, selectEmployeeByProcessId, updateProcessEmployee } from '@/api/process'
import SelectEmployee from '@/components/modules/selectEmployee.vue'
import { selectByShiftIdAndOutputDate } from '@/api/output'
import { Dialog } from 'vant'

export default {
  name: 'PieceRateWageCalculateModule',
  components: { SelectEmployee },
  data() {
    return {
      showProcess: false,
      showShift: false,
      showDate: false,
      showEmployee: false,
      title: '',
      submitForm: {},
      shiftList: [],
      processList: [],
      employeeList: [],
      minDate: moment(new Date()).subtract(30, 'years').toDate()
    }
  },
  methods: {
    init() {
      this.selectAllProcess()
      this.selectAllShift()
      this.resetForm()
      this.title = '计算计件工资'
    },
    resetForm() {
      this.employeeList = []
      this.submitForm = {
        employeeIds: [],
        quantity: '',
        unitPrice: '',
        shiftId: '',
        date: '',
        subsidy: ''
      }
    },
    doSubmit() {
      Dialog.confirm({
        title: '确认提醒',
        message: '请确认当日班次产量数据已录入完毕?重新计算会覆盖之前的计算结果'
      }).then(() => {
        calculatePieceRateWage(this.submitForm).then(resp => {
          if (resp.success) {
            this.$toast.success('操作成功')
            this.$emit('close')
          }
        })
      }).catch(() => {})
    },
    onConfirmDate(row) {
      this.submitForm.date = Moment(row).format('YYYY-MM-DD')
      this.showDate = false
      this.selectByShiftIdAndOutputDate()
    },
    onShiftConfirm(row) {
      this.submitForm.shiftId = row.id
      this.submitForm.shiftName = row.name
      this.showShift = false
      this.selectByShiftIdAndOutputDate()
    },
    onProcessConfirm(row) {
      this.submitForm.processId = row.id
      this.submitForm.processName = row.name
      this.showProcess = false
      this.getProcessUnitPrice()
      selectEmployeeByProcessId(row.id).then(resp => {
        if (resp.success) {
          this.employeeList = []
          this.submitForm.employeeIds = []
          resp.data.forEach(item => {
            item.show = true
            this.employeeList.push(item)
            this.submitForm.employeeIds.push(item.id)
          })
        }
      })
    },
    selectAllShift() {
      selectAllShift().then(resp => {
        if (resp.success) {
          this.shiftList = resp.data
        }
      })
    },
    selectAllProcess() {
      selectAllProcess().then(resp => {
        if (resp.success) {
          this.processList = resp.data
        }
      })
    },
    handleRemoveEmployee(employee) {
      this.employeeList.splice(this.employeeList.indexOf(employee), 1)
      this.submitForm.employeeIds.splice(this.submitForm.employeeIds.indexOf(employee.id), 1)
      this.bindingEmployeeForProcess()
    },
    bindingEmployeeForProcess() {
      const requestData = { processId: this.submitForm.processId, employeeIds: this.submitForm.employeeIds }
      updateProcessEmployee(requestData).then(resp => {
        if (resp.success) {
          this.$toast.success('操作成功')
        }
      })
    },
    handleCloseEmployee(data) {
      this.showEmployee = false
      if (!data) {
        return
      }
      data.forEach(item => {
        if (this.submitForm.employeeIds.indexOf(item.id) === -1) {
          this.employeeList.push(item)
          this.submitForm.employeeIds.push(item.id)
        } else {
          this.$toast.fail('员工:' + item.employeeName + '，已存在，请不要重复选择！')
        }
      })
      this.bindingEmployeeForProcess()
    },
    selectByShiftIdAndOutputDate() {
      if (this.submitForm.date !== '' && this.submitForm.shiftId !== '') {
        const data = { shiftId: this.submitForm.shiftId, outputDate: this.submitForm.date }
        selectByShiftIdAndOutputDate(data).then(resp => {
          if (resp.success) {
            this.submitForm.quantity = resp.data
          }
        })
      }
    },
    getProcessUnitPrice() {
      if (this.submitForm.processId) {
        this.submitForm.unitPrice = this.processList.filter(e => e.id === this.submitForm.processId)[0].unitPrice
      }
    }
  }
}
</script>

<style scoped>

</style>
